<?php

use console\db\Migration;
use yii\db\Query;
use yii\helpers\Console;

/**
 * 生成“记住密码”时的认证密钥
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300000_000004_t_user_generate_authkey extends Migration {

    const BATCH_SIZE = 1000;

    /**
     * @inheritdoc
     */
    public $tableName = '{{%user}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from($this->tableName)->select(['id'])->where(['auth_key' => null]);
        Console::output("update auth_key running...");
        $this->handleProgress($query, [$this, 'evenDule']);
        Console::output("update done.");
    }

    /**
     * @inheritdoc
     */
    public function safeDown() {
        $this->update($this->tableName, ['auth_key' => null]);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        foreach ($rows as $user) {
            $migration->db->createCommand()->update($migration->tableName, [
                'auth_key' => Yii::$app->security->generateRandomString()
            ], ['id' => $user['id']])->execute();
        }
    }

    /**
     * 生成“记住密码”时的认证密钥 
     */
    public function generateAuthKey() {
        return Yii::$app->security->generateRandomString();
    }

}
